import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

interface UserState {
  loading: boolean
  token: string | null
  userInfo: UserInfoState
  routes: UserRouteState[]
}

interface UserInfoState {
  id: number | string,
  user: string,
  role_id: number | string,
  user_name: string,
  role_name: string,
}

export interface UserRouteState {
  id: number | string
  ps_api_path: string
  ps_id: number | string
  ps_level: number | string
  ps_name: string
  ps_pid: number | string
  ps_api_service: string
  children?: UserRouteState[]
}


const initialState: UserState = {
  loading: false,
  userInfo: {
    id: '',
    user: '',
    role_id: '',
    user_name: '',
    role_name: '',
  },
  token: '',
  routes: []
};

interface DataState {
  user: string;
  pwd: string;
}

export const login = createAsyncThunk(
  "user/login",
  async (data: DataState) => {
    try {
      const resp = await axios.post("/api/login", data);
      return resp.data;
    } catch (e) {
      return Promise.reject(e)
    }
  }
);

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    verifySuccess(state, action) {
      state.loading = false
      state.routes = action.payload.data.routes
      state.userInfo = action.payload.data.userInfo
    },
    verifyFail(state) {
      state.loading = false
      state.routes = []
      state.token = ''
      state.userInfo = {
        id: '',
        user: '',
        role_id: '',
        user_name: '',
        role_name: '',
      }
    }
  },
  extraReducers: {
    [login.pending.type](state) {
      state.loading = true
    },
    [login.fulfilled.type](state, action) {
      state.loading = false
      state.token = action.payload.data.token
      state.userInfo = action.payload.data.userInfo
    },
    [login.rejected.type](state) {
      state.loading = false
      state.routes = []
      state.token = ''
      state.userInfo = {
        id: '',
        user: '',
        role_id: '',
        user_name: '',
        role_name: '',
      }
    }
  }
});

export default userSlice.reducer;
export const { verifyFail, verifySuccess } = userSlice.actions
